import Icon from '@/components/MyIcon'
import { NavBar, Input } from 'antd-mobile'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import { useEffect, useRef, useState } from 'react'
import { useInitState } from '@/utils/hooks'
import { userProfileAction } from '@/store/action/profile'

import io, { Socket } from 'socket.io-client'
import { getToken } from '@/utils/auth'
let client: Socket
const Chat = () => {
  const history = useHistory()
  // 获取用户信息
  const { profile } = useInitState(userProfileAction(), 'profile')
  const [input, setInput] = useState('')
  const scrollRef = useRef<HTMLDivElement>(null)
  // 初始数组
  const [mesList, setMesList] = useState<
    {
      type: 'robot' | 'user'
      text: string
    }[]
  >([
    {
      type: 'robot',
      text: '亲爱的用户,有什么需要我帮您的呢?',
    },
    {
      type: 'user',
      text: '你好吗?',
    },
  ])
  const submitMsg = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && input !== '') {
      client.emit('message', { timestamp: Date.now(), msg: input })
      setMesList((mesList) => {
        return [...mesList, { type: 'user', text: input }]
      })
    }
  }
  useEffect(() => {
    client = io('http://toutiao.itheima.net', {
      query: {
        token: getToken().token,
      },
      transports: ['websocket'],
    })
    client.on('connect', () => {
      console.log('简历链接')
    })
    client.on('message', (data) => {
      console.log('接受消息')
      setMesList((mesList) => {
        return [
          ...mesList,
          {
            type: 'robot',
            text: data.msg,
          },
        ]
      })
    })

    client.on('disconnect', () => {
      console.log('断开链接')
    })
    // setTimeout(() => {
    //   client.emit('message', { timestamp: Date.now(), msg: '你好好' })
    // }, 1000)
  }, [])
  useEffect(() => {
    const current = scrollRef.current!
    current.scrollTop = current.scrollHeight
  }, [mesList])
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header" onBack={() => history.go(-1)}>
        小智同学
      </NavBar>

      {/* 聊天记录列表 */}
      <div ref={scrollRef} className="chat-list">
        {mesList.map((v, index) => {
          if (v.type === 'robot') {
            return (
              <div key={index} className="chat-item">
                <Icon type="iconbtn_xiaozhitongxue" />
                <div className="message">{v.text}</div>
              </div>
            )
          } else {
            return (
              <div key={index} className="chat-item user">
                <img src={profile.photo} alt="" />
                <div className="message">{v.text}</div>
              </div>
            )
          }
        })}
        {/* 机器人的消息 */}

        {/* 用户的消息 */}
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <Input
          className="no-border input"
          placeholder="请描述您的问题"
          value={input}
          onChange={(value) => setInput(value)}
          onKeyUp={submitMsg}
        />
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat
